﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// 功能:会员统计
/// 开发者:耿卫星
/// </summary>
public partial class Statistics_MemberStatistics : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        Page.Theme = BLL.Common.GetWSMThemes();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        Check.CheckPermission("900400");
        if (!IsPostBack)
        {
            TextBox2.Attributes.Add("onclick", "MultiSearchVIP('../');");
            txtType.Attributes.Add("onclick", "SelectCard('../')");
            List<Model.ORDERFROM> lst = new BLL.ORDERFROM().GetAllList(false);
            drpOrderFrom.Items.Add(new ListItem("全部", ""));
            foreach (Model.ORDERFROM order in lst)
            {
                drpOrderFrom.Items.Add(new ListItem(order.OF_NAME, order.OF_CODE));
            }  
            //绑定支付方式
            //Bind();
        }
        Session["FCode"] = "900400";
    }
    /// <summary>
    ///会员统计
    ///usp_PagingLarge分页存储过程，可支持多表查询，任意排序 ,和统计功能
    /// </summary>
    /// <param name="startIndex">当前页</param>
    /// <param name="pageSize">每页多少记录</param>
    /// <param name="Filter">查询条件</param>
    private void Bind( bool IsExport)
    {
        //根据支付方式查出相关的订单编号
        string sqlstr = "";
        if (TextBox2.Text.Contains(","))
        {
            string[] tem = TextBox2.Text.Trim().Split(',');
            int i = 0;
            foreach (string temtext in tem)
            {
                if (temtext.Trim() != "")
                {
                    if (i == 0)
                    {
                        sqlstr = sqlstr + " and ( V_CUSTOMER.dm  like '%" + temtext + "%' ";
                    }
                    else
                    {
                        sqlstr = sqlstr + " or  V_CUSTOMER.dm  like '%" + temtext + "%' ";
                    }
                    i++;
                }
            }
        }
        else
        {
            sqlstr += TextBox2.Text.Trim() == "" ? "" : " and  ( V_CUSTOMER.dm  like '%" + TextBox2.Text.Trim() + "%' ";
        }
        if (sqlstr.Trim() != "")
        {
            sqlstr = sqlstr + ") ";
        }

        StringBuilder str = new StringBuilder();
        if (hdtxtType.Value.Length > 0)
        {
            string[] arrType = hdtxtType.Value.TrimEnd(',').Split(',');
            foreach (string item in arrType)
            {
                str.Append("'" + item + "',");
            }
        }
        sqlstr += str.ToString().Length == 0 ? "" : " and V_CARSET.DM IN(" + str.ToString().Substring(0,str.ToString().Length-1) + ")"; ;
        sqlstr += drpOrderFrom.SelectedValue == "" ? "" : " and OF_CODE='"+drpOrderFrom.SelectedValue+"'";
        #region 组织日期条件
        if (txtStart.Text.Trim().Length > 0 || txtEnd.Text.Trim().Length > 0)
        { sqlstr += " AND ORDER_CREATEDATE between '" + txtStart.Text.Trim() + "' and '" + DateTime.Parse(txtEnd.Text.Trim()).AddDays(1) + "'"; }
        if (txtDate1.Text.Trim().Length > 0 || txtDate2.Text.Trim().Length > 0)
        { sqlstr += " AND ORDER_CHECKDATE between '" + txtDate1.Text.Trim() + "' and '" + DateTime.Parse(txtDate2.Text.Trim()).AddDays(1) + "'"; }
        if (txtDate3.Text.Trim().Length > 0 || txtDate4.Text.Trim().Length > 0)
        { sqlstr += " AND ORDER_SENDDATE between '" + txtDate3.Text.Trim() + "' and '" + DateTime.Parse(txtDate4.Text.Trim()).AddDays(1) + "'"; }
        #endregion
        /*
        sqlstr += txtStart.Text.Trim() == "" ? " and (ORDERDOC.ORDER_SENDDATE>'1900-01-01' " : " and (ORDERDOC.ORDER_SENDDATE>='" + txtStart.Text.Trim() + "' ";
        sqlstr += txtEnd.Text.Trim() == "" ? " and ORDERDOC.ORDER_SENDDATE<'2099-01-01') " : " and ORDERDOC.ORDER_SENDDATE<='" + DateTime.Parse(txtEnd.Text.Trim()).AddDays(1).ToShortDateString() + "') ";
        */    
        int pageCount, rowCount;
        //DataSet properties = new BLL.ORDERDOC().GetList2("orderdoc left join PAYDETAIL on ORDER_ID=PD_ID  left join ORDERDETAIL on order_id=od_id ", "orderdoc.*", false, AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, "ORDER_CREATEDATE", true, sqlstr, out pageCount, out rowCount);
             
        DataSet properties = new BLL.ORDERDOC().P_GetMemberStatisticsList(Convert.ToString(AspNetPager1.StartRecordIndex-1), AspNetPager1.PageSize.ToString(), sqlstr);
        rowCount = properties.Tables[0].Rows.Count;
        if (IsExport)
        {
            DataTable2Excel(properties.Tables[0]);
        }
        pageCount = rowCount / AspNetPager1.PageSize;
        MemberStatisticsControl1.Bind(properties.Tables[0]);
        AspNetPager1.RecordCount = 1;
    }
    protected void DataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        e.Item.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
        e.Item.Cells[2].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
        e.Item.Cells[6].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
        e.Item.Cells[7].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
    }

    /// <summary>
    /// DataTable导出Excel
    /// </summary>
    /// <param name="dtData"></param>
    public   void DataTable2Excel(System.Data.DataTable dtData)
    {
        System.Web.UI.WebControls.DataGrid dgExport = null;
        System.Web.HttpContext curContext = System.Web.HttpContext.Current;
        System.IO.StringWriter strWriter = null;
        System.Web.UI.HtmlTextWriter htmlWriter = null;

        if (dtData != null)
        {
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
            curContext.Response.Charset = "";

            //dtData.Rows.RemoveAt(0);
            strWriter = new System.IO.StringWriter();
            htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

            dgExport = new System.Web.UI.WebControls.DataGrid();

            //dtData.Columns.Add("发放状态");
            ////dtData.Columns.Add("财务审核");
            ////dtData.Columns.Add("结算");
            dtData.Columns["id_PageRowID"].ColumnName = "序号";
            dtData.Columns["DM"].ColumnName = "会员帐号";
            dtData.Columns["GKMC"].ColumnName = "会员名";
            dtData.Columns["MC"].ColumnName = "VIP卡类型";
            dtData.Columns["OF_NAME"].ColumnName = "订单来源";
            dtData.Columns["OrderCount"].ColumnName = "订单数";
            dtData.Columns["OrderQTY"].ColumnName = "销售件数";

            dtData.Columns["OrderTAMT"].ColumnName = "销售额";
            dtData.Columns["DH"].ColumnName = "电话";
            dtData.Columns["EMAIL"].ColumnName = "电子邮件";
            //////dtData.Columns["Aprice"].ColumnName = "实际单价";
            //////dtData.Columns["Samt"].ColumnName = "标准金额";
            //////dtData.Columns["Aamt"].ColumnName = "实际金额";
            //for (int i = 0; i < dtData.Rows.Count; i++)
            //{
            //    //dtData.Rows[i]["发货/入库"] = dtData.Rows[i]["SendOrReceive"].ToString() == "1" ? "已发货" : "未发货"; 
            //    dtData.Rows[i]["发放状态"] = dtData.Rows[i]["SENDFLAG"].ToString() == "1" ? "已发放" : "未发放";
            //}
            //////移除列
            //dtData.Columns.Remove(dtData.Columns["SENDFLAG"]); 
            //dgExport.DataSource = dtData.DefaultView;
            //dgExport.AllowPaging = false;
            //dgExport.DataBind();
            //dgExport.RenderControl(htmlWriter);

            this.DataGrid.DataSource = dtData.DefaultView;
            this.DataGrid.AllowPaging = false;
            this.DataGrid.DataBind();
            this.DataGrid.RenderControl(htmlWriter);
            curContext.Response.Write(strWriter.ToString());
            curContext.Response.End();
        }
    } 

    protected void Button1_Click(object sender, EventArgs e)
    {
        if ((txtStart.Text.Trim().Length < 1 || txtEnd.Text.Trim().Length < 1) && (txtDate1.Text.Trim().Length < 1 || txtDate2.Text.Trim().Length < 1) && (txtDate3.Text.Trim().Length < 1 || txtDate4.Text.Trim().Length < 1))
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert(\"请至少输入一个起止日期\")", true);
            return;
        }
        Bind(false);
    }

    protected void Export_Click(object sender, EventArgs e)
    {
        if ((txtStart.Text.Trim().Length < 1 || txtEnd.Text.Trim().Length < 1) && (txtDate1.Text.Trim().Length < 1 || txtDate2.Text.Trim().Length < 1) && (txtDate3.Text.Trim().Length < 1 || txtDate4.Text.Trim().Length < 1))
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert(\"请至少输入一个起止日期\")", true);
            return;
        }
        Bind(true);
    }

    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        Bind(false);
        //int pageCount, rowCount;
        //List<Model.ORDERDOC> properties = new BLL.ORDERDOC().GetList(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, "ORDER_ID", false, "", out pageCount, out rowCount);
        //ORDERDOCListControl1.Bind(colors);
    }

    protected void btngjcx_Click(object sender, EventArgs e)
    {

    }
    protected void Button3_Click(object sender, EventArgs e)
    {

    }
}
